package com.well.kernel.service;

import com.well.kernel.mybatis.mapper.ABaseMapper;
import com.well.kernel.mybatis.persistence.ABaseEntity;
import com.well.kernel.mybatis.mapper.genid.IDGenerator;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;
import java.util.List;

/**
 * Copyright &copy; Well All rights reserved.
 * Author:Well
 * Date:2016/12/29
 * Description:业务层抽象基类，对应的泛型实体必须继承 com.well.kernel.mybatis.persistence.ABaseEntity
 */

public abstract class ABaseService<T extends ABaseEntity> extends AbstractService<T>
{
    private static Logger logger=Logger.getLogger(ABaseService.class);

    @Autowired
    private ABaseMapper<T> aBaseMapper;

    @Override
    public int insert(T entity)
    {
    	Date date=new Date();
        if(StringUtils.isEmpty(entity.getId())){
            entity.setId(IDGenerator.uuid());
        }
    	entity.setInsertDate(date);
    	entity.setUpdateDate(date);
        if(null==entity.getEnable()){
            entity.setEnable(1);
        }
    	return super.insert(entity);
    }
    
    @Override
    public int insertSelective(T entity) 
    {
        Date date=new Date();
        if(StringUtils.isEmpty(entity.getId())){
            entity.setId(IDGenerator.uuid());
        }
        entity.setInsertDate(date);
        entity.setUpdateDate(date);
        if(null==entity.getEnable()){
            entity.setEnable(1);
        }
    	return super.insertSelective(entity);
    }

    public int delete(String id)
    {
    	if(StringUtils.isEmpty(id))
    	{
    		logger.warn("主键为空，无法删除！");
    		return 0;
    	}
    	return super.delete(id);
    }

    /**
     * 根据主键集合进行逻辑批量删除
     * 将 enable 字段置为0
     * @param idList
     * @return
     */
    public int logicalDelete(List<String> idList)
    {
        if(null==idList || idList.size()==0){
            logger.warn("主键列表为空，无法逻辑删除！");
            return 0;
        }
        return aBaseMapper.logicalDelete(idList);
    }

    @Override
    public int update(T entity)
    {
    	if(StringUtils.isEmpty(entity.getId()))
    	{
    		logger.warn("主键为空，无法更新！");
    		return 0;
    	}
    	entity.setUpdateDate(new Date());
    	return super.update(entity);
    }
    
    @Override
    public int updateSelective(T entity) 
    {
    	if(StringUtils.isEmpty(entity.getId()))
    	{
    		logger.warn("主键为空，无法选择性更新！");
    		return 0;
    	}
    	entity.setUpdateDate(new Date());
    	return super.updateSelective(entity);
    }

    public T select(String id) 
    {
    	if(StringUtils.isEmpty(id))
    	{
    		logger.warn("主键为空，无法查询！");
    		return null;
    	}
    	return super.select(id);
    }

}
